package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.manager.HttpCallBack;

import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.MyHalfRoundProgressBar;
import com.kkd.kkdapp.view.EditText.FinanceEditText;

/**
 * 天天赚提现
 * 
 * @author mty
 * 
 */
public class Everyday_WithdrawActivity extends BaseActivity implements
		OnClickListener {

	private final int BALANCE_CODE_ZERO = 7;
	private Dialog mDialog;
	private TextView withdraw_balance;
	private FinanceEditText withdraw_money;
	private Button withdraw_bt; // 　提交
	private RelativeLayout withdraw_title; // 返回
	private String myYuebaoBalance = null;
	private boolean SUBMITFLAG = false;
	private AlertDialog dialog;
	private boolean SUBMITlimit = true;
	private int dialogint;
	private static final int DECIMAL_DIGITS = 2; // 输入框小数的位数
	// private MyHalfRoundProgressBar roundProgressBar;
	private long sellFreeAmoutLine; // 今日总限额
	private long sellFreeAmout; // 剩余限额
	private TextView rental;
	private DecimalFormat df = new DecimalFormat("0.00");
	private DecimalFormat df1 = new DecimalFormat("###,###.00");
	private TextView residue;
	private String desc;
	private String yuebaoBalance;
	private String timeLimitDesc;
	private TextView balance_tv;
	private ImageView pointer;
	private double sellRates;
	private long sellLimitAmount;
	private TextView excess_tv;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				withdraw_bt.setEnabled(true);
				SUBMITFLAG = true;
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			case 2:
				PreferenceUtils.getInstance().setMyproperty(
						Everyday_WithdrawActivity.this, "");
				Intent intent_toTip = new Intent(
						Everyday_WithdrawActivity.this,
						WithdrawSuccessTipActivity.class);
				intent_toTip
						.putExtra("amount", Double.parseDouble(withdraw_money
								.getText().toString()));
				startActivity(intent_toTip);
				finish();
				// showToast("转出成功");
				// mHandler.postDelayed(new Runnable() {
				//
				// @Override
				// public void run() {
				// finish();
				// }
				// }, 2000);
				break;
			case 3:
				desc = (String) msg.obj;
				showToast(desc);
				if (loadDialog != null && loadDialog.isShowing()) {
					loadDialog.dismiss();
				}
				break;
			case 4:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			case 5:
				showToast(desc);
				break;
			case 6:
				myYuebaoBalance = yuebaoBalance;
				withdraw_balance.setText(yuebaoBalance);
				break;
			case BALANCE_CODE_ZERO:
				String balance = (String) msg.obj;
				balance_tv.setText(balance);
				break;
			default:
				break;
			}
		};
	};
	private RelativeLayout tip_top;
	private TextView hint_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_everyday__withdraw_new);
		initView();
		getMessage();
		setListener();
	}

	public void initView() {
		withdraw_balance = (TextView) this.findViewById(R.id.withdraw_balance);
		tip_top = (RelativeLayout) this.findViewById(R.id.tip_top);
		withdraw_money = (FinanceEditText) this
				.findViewById(R.id.withdraw_money);
		withdraw_bt = (Button) this.findViewById(R.id.withdraw_bt);
		withdraw_title = (RelativeLayout) this
				.findViewById(R.id.withdraw_title_img);
		// roundProgressBar = (MyHalfRoundProgressBar) this
		// .findViewById(R.id.progressbar);
		// roundProgressBar.setMax(100);
		rental = (TextView) this.findViewById(R.id.rental);
		residue = (TextView) this.findViewById(R.id.residue);
		hint_tv = (TextView) this.findViewById(R.id.hint_tv);
		balance_tv = (TextView) this.findViewById(R.id.balance_tv);
		pointer = (ImageView) this.findViewById(R.id.pointer);
		excess_tv = (TextView) this.findViewById(R.id.excess_tv);
	}

	@Override
	protected void onResume() {
		super.onResume();

		getAccountInfo();

	}

	public void getMessage() {
		Intent intent = getIntent();
		myYuebaoBalance = intent.getStringExtra("myYuebaoBalance");
		if (!"".equals(myYuebaoBalance)) {
			withdraw_balance.setText(myYuebaoBalance);
		}
		sellFreeAmoutLine = intent.getLongExtra("sellFreeAmoutLine", 0);
		rental.setText(df1.format(sellFreeAmoutLine * 0.01));
		if (sellFreeAmoutLine == 0) {
			rental.setText("0.00");
		}
		sellFreeAmout = intent.getLongExtra("sellFreeAmout", 0);
		residue.setText(df1.format(sellFreeAmout * 0.01));
		if (sellFreeAmout == 0) {
			residue.setText("0.00");
		}
		sellRates = intent.getDoubleExtra("sellRates", 0);
		LogUtil.e("sellRates", sellRates + "");
		// if (100 - sellRates * 100 < 1 && 100 - sellRates * 100 > 0) {
		// roundProgressBar.withNumber(1);
		// } else {
		// roundProgressBar.withNumber((int) (100 - sellRates * 100));
		// }
		// roundProgressBar.setDuration(1000);
		// roundProgressBar.start();
		timeLimitDesc = intent.getStringExtra("timeLimitDesc");
		if (sellFreeAmout == 0) {
			tip_top.setVisibility(View.VISIBLE);
			hint_tv.setVisibility(View.GONE);
		} else {
			if (TextUtils.isEmpty(timeLimitDesc)) {
				hint_tv.setVisibility(View.GONE);
			} else {
				hint_tv.setVisibility(View.VISIBLE);
				hint_tv.setText(timeLimitDesc);
			}
			tip_top.setVisibility(View.GONE);
		}
		sellLimitAmount = intent.getLongExtra("sellLimitAmount", -1);
		rotationAnimtor();
	}

	public void setListener() {
		withdraw_bt.setOnClickListener(this);
		withdraw_title.setOnClickListener(this);
		// withdraw_money.setFilters(new InputFilter[] { lengthfilter });
		withdraw_money.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!"".equals(myYuebaoBalance) && myYuebaoBalance != null) {
					if (!"".equals(withdraw_money.getText().toString())) {
						if (decimals(s.toString())) {
							if ("0.00".equals(myYuebaoBalance)) {
								if (".".equals(s.toString())) {
									withdraw_money.setText("0.");
									withdraw_money.setSelection(withdraw_money
											.length());
								} else if (Double.parseDouble(withdraw_money
										.getText().toString()) == 0) {
									withdraw_bt.setEnabled(false);
									SUBMITFLAG = false;
								} else {
									if (Double.parseDouble(s.toString()) > Double
											.parseDouble(myYuebaoBalance)) {
										showDialog("您余额为" + (myYuebaoBalance)
												+ "，无法转出");
										dialogint = 1;
									}
								}
							} else {
								if (".".equals(s.toString())) {
									withdraw_money.setText("0.");
									withdraw_money.setSelection(withdraw_money
											.length());
								} else {
									if (Double.parseDouble(withdraw_money
											.getText().toString()) == 0) {
										withdraw_bt.setEnabled(false);
										SUBMITFLAG = false;
									} else {
										if (Double.parseDouble(s.toString()) > Double
												.parseDouble(myYuebaoBalance)) {
											showDialog("您最多可转出"
													+ (myYuebaoBalance) + "元");
											withdraw_money
													.setText(myYuebaoBalance);
											withdraw_money
													.setSelection(withdraw_money
															.getText()
															.toString()
															.length());
										} else {
											if (sellLimitAmount != -1) {
												if (Double.parseDouble(s
														.toString()) > sellLimitAmount * 0.01) {
													excess_tv
															.setVisibility(View.VISIBLE);
													excess_tv.setText("输入金额大于个人限额,今日可转出"
															+ df.format(sellLimitAmount * 0.01)
															+ "元");
												} else {
													excess_tv
															.setVisibility(View.GONE);
													if (!"".equals(withdraw_money
															.getText()
															.toString())
															&& Double
																	.parseDouble(s
																			.toString()) > 0) {
														withdraw_bt
																.setEnabled(true);
														SUBMITFLAG = true;
													}

												}
											} else {
												excess_tv
														.setVisibility(View.GONE);
												if (!"".equals(withdraw_money
														.getText().toString())
														&& Double.parseDouble(s
																.toString()) > 0) {
													withdraw_bt
															.setEnabled(true);
													SUBMITFLAG = true;
												}

											}
										}
									}

								}
							}
						} else {
							String dValue = s.toString();
							String[] splitArray = dValue.split("\\.");
							String newValue;
							if (splitArray.length > 1) {
								newValue = splitArray[0] + "." + splitArray[1];
							} else {
								newValue = splitArray[0] + ".";
							}
							String[] splitArray2 = newValue.split("\\.");
							if (splitArray2.length > 1) {
								String dotValue = splitArray2[1];
								int diff = dotValue.length() - DECIMAL_DIGITS;
								if (diff < 0)
									diff = 0;
								newValue = newValue.substring(0,
										splitArray2[0].length()
												+ splitArray2[1].length() + 1
												- diff);

							}
							withdraw_money.setText(newValue);
							withdraw_money.setSelection(withdraw_money
									.getText().toString().length());
						}
					} else {
						withdraw_bt.setEnabled(false);
						SUBMITFLAG = false;
					}
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				String temp = s.toString();
				int posDot = temp.indexOf(".");
				if (posDot <= 0) {
					if (temp.length() <= 8) {
						return;
					} else {
						s.delete(8, 9);
						return;
					}
				}
			}
		});
	}

	InputFilter lengthfilter = new InputFilter() {

		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {

			// 删除等特殊字符，直接返回
			if ("".equals(source.toString())) {
				return null;
			}
			String dValue = dest.toString();
			String[] splitArray = dValue.split("\\.");
			if (splitArray.length > 1) {
				String dotValue = splitArray[1];
				int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
				if (diff > 0) {
					return source.subSequence(start, end - diff);
				}
			}
			return null;
		}

	};
	private Dialog loadDialog;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.withdraw_bt:
			SystemUtils.onEvent("Account_Current_TransferOutPage_Submit", 1);
			if (SUBMITlimit) {
				SUBMITlimit = false;
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						SUBMITlimit = true;
					}
				}, 2000);
				if (SUBMITFLAG) {
					requestRedeem();
				}
			}
			break;
		case R.id.withdraw_title_img:
			finish();
			break;
		}
	}

	/**
	 * 天天赚取现
	 */
	public void requestRedeem() {
		withdraw_bt.setEnabled(false);
		SUBMITFLAG = false;
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(Everyday_WithdrawActivity.this,
				"提交中，请耐心等候...");

		KkdHttpMagager.getInstance()
				.getEverydayWithdrawManager(
						(long) (Double.parseDouble(withdraw_money.getText()
								.toString()) * 100), String.class,
						new HttpCallBack() {

							@Override
							public void onSuccess(int statusCode,
									Object responseBody) {
								mHandler.sendEmptyMessage(1);
								mHandler.sendEmptyMessage(2);
							}

							@Override
							public void onFailure(int statusCode, String desc) {
								Message msg = new Message();
								msg.obj = desc;
								msg.what = 3;
								if (statusCode == 219) {
									requestQueryYuebaoInfo();
								}
								mHandler.sendMessage(msg);
							}
						});
	}

	public void showDialog(String message) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscribeDialog(Everyday_WithdrawActivity.this,
				message, new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (dialogint == 1) {
							finish();
						}
						mDialog.dismiss();
					}
				});
		mDialog.show();
	}

	/**
	 * 天天赚主页面
	 */
	public void requestQueryYuebaoInfo() {
		KkdHttpMagager.getInstance().getAccounEverydayManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object res) {
						String responseString = res.toString();
						try {
							JSONObject mJSONObject = new JSONObject(
									responseString);
							if (mJSONObject.getInt("code") == 0) {
								JSONObject data = mJSONObject
										.getJSONObject("data");
								int myYuebaoBalance = data
										.getInt("myYuebaoBalance");
								yuebaoBalance = df
										.format(myYuebaoBalance * 0.01);
								mHandler.sendEmptyMessage(6);
							} else {
								desc = mJSONObject.getString("desc");
								mHandler.sendEmptyMessage(5);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String responseBody) {

					}
				});
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		KkdHttpMagager.getInstance().getAccountInfoManager( String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							DecimalFormat df = new DecimalFormat("0.00");
							JSONObject data = new JSONObject(responseString);
							double balance = data.getDouble("balance");
							String bmouts = df.format(balance);
							Message msg = new Message();
							msg.obj = bmouts;
							msg.what = BALANCE_CODE_ZERO;
							mHandler.sendMessage(msg);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				});
	}

	public void rotationAnimtor() {
		BitmapDrawable bd = (BitmapDrawable) this.getResources().getDrawable(
				R.drawable.pointer_img);
		int toRadian = 0;
		// if (180 * (int) (100 - sellRates * 100) / 100 > 176) {
		// toRadian = -176;
		// } else {
		// if (100 - sellRates * 100 < 1 && 100 - sellRates * 100 > 0) {
		// toRadian = -1;
		// } else {
		// toRadian = -180 * (int) (100 - sellRates * 100) / 100;
		// }
		// }
		toRadian = -180 * (int) (100 - sellRates * 100) / 100;

		// RotateAnimation animation = new RotateAnimation(0F, toRadian, bd
		// .getBitmap().getWidth() / 2, bd.getBitmap().getHeight() / 2);
		// animation.setDuration(1000);
		// animation.setFillAfter(true);
		// pointer.setAnimation(animation);
		// animation.start();
		ObjectAnimator anim = ObjectAnimator.ofFloat(pointer, "rotation", 0,
				toRadian);
		anim.setDuration(1000);
		anim.setRepeatMode(ObjectAnimator.RESTART);
		anim.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
	}
}
